<template>
  <el-container class="paper-page">
    <el-header>
      <common-header></common-header>
    </el-header>

    <div>
      <el-header class="paper-header">
            
            <div clas="page-title_2"><h1>学生姓名:{{this.$route.query.studentName}} 学号:{{this.$route.query.studentId}}   当前选择试卷:</h1>   
            </div>
            <div class="select-exer">
              <el-select v-model="nowExer" placeholder="请选择试卷" @change="selectExer">
                <el-option
                v-for="(item,index) in AllExerAnswer"
                :key="index"
                :label="item.name"
                :value="item.exerciseId"
                >
                </el-option>
            </el-select>  
            </div>
          <el-button type="primary" @click="saveAsExcel">导出excel</el-button> 
           <div style="margin-left: auto;color: red;" ><h3 >总分{{studentScore}}(满分:{{sumScore}})</h3></div> 
            
        </el-header>
    </div>

    <el-main class="paper-main">
      <!-- 静态生成表格列 -->
      <el-table
        :header-cell-style="{
          fontSize: '18px',
        }"
        :cell-style="{
          fontFamily: 'MicroSoft YaHei',
          fontSize: '18px',
        }"
        :key="itemkey"
        :data="tableData"
        :fit="true"
        style="width: 100%"
        class="result-table"
        :class="getClass(-1)"
      >
        <el-table-column  prop="orderId" label="序号"  width="60" >
        </el-table-column>
        <el-table-column prop="questionId" label="题目编号"  width="100">
            <template slot-scope="scope">
               <div>
                 <a href="#" @click="questionClick(scope.row)">{{scope.row.questionId}}</a>
               </div>
             </template>
        </el-table-column>
        
        <el-table-column prop="dbName" label="大题名称" width="150" >
        </el-table-column>
       
        <el-table-column prop="difficulty" label="难易度" >
        </el-table-column>
        <el-table-column prop="refanswer"  label="参考答案" width="400" >
        </el-table-column> 

        <el-table-column prop="answer"  label="学生答案"  width="400" >
        </el-table-column>
        <el-table-column prop="idea" label="作答思路"  width="400">
        </el-table-column>
        <el-table-column  prop="isRight" label="是否正确"  width="100" >
          <template slot-scope="scope">
               <div>
                 <a href="#" @click="rightClick(scope.row)">{{formatBoolean(scope.row.isRight)}}</a>
               </div>
             </template>
        </el-table-column>
        
        <el-table-column   prop="score" label="得分"  width="100">
            <template slot-scope="scope">
               <div>
                 <a href="#" @click="scoreClick(scope.row)">{{scope.row.score}}</a>
               </div>
             </template>
        </el-table-column>
      </el-table>
      <el-dialog  title="修改分数" :visible.sync="dialogFormVisible">
                 <el-form :model="form">
                
                <el-form-item
                  label="分数"
                  :label-width="formLabelWidth"
                >
                  <el-input
                    v-model="form.score"
                    placeholder="请输入分数，在0-100之间"
                    
                  ></el-input>
                </el-form-item>
                
              </el-form>
              
                <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>

                <el-button type="primary" @click="modifyScoreClick"
                  >确 定</el-button
                >
              </div>
              
              
            </el-dialog>
     
    </el-main>
  </el-container>
</template>

<script>
import CommonHeader from "../components/CommonHeader.vue";


import { getStudentExerAnswer,getExerSumScore,getOneStudentById, getClassAllExers} from "@/api/api.js";
import { getStudentAllAnswer,getTeachers } from "@/api/api.js";
import { modifyStudentScore,modifyScoreToLog } from "@/api/api.js";
import { modifyStudentAnswer } from "@/api/api.js";
import { table2Excel, JSonToCSV } from "../util/utils.js";
export default {
  components: {
    CommonHeader,
  },
  data() {
    return {
      itemkey:'', 
      req:{
        id:this.$store.state.username
      },
      request: {
        studentId:'',
        exerciseId:'',
        questionId:'',
        score:''
      },
      nowExer:'',
      AllExerAnswer:[],
      tableData: [],
      tableLable: {
       refanswer:'参考答案',
       score:'得分',
       isRight:'是否正确',
       questionId:'题目编号',
       answer:'做答结果',
       orderId:'题目顺序序号',
       questionClass:'题目类别',
       idea:'作答思路',
       dbName:'所在数据库',
       title:'题目标题'
      },
      sumScore:0,
      studentScore:0,
      dialogFormVisible: false,
      form: {
       score:''

      },
      difficulty:'',
      tname:'',
      formLabelWidth: "120px",
      answer:'',
      stuanswer:'',
      stuidea:'',
      oldscore:'',
      newscore:'',
      classId:''
    };
  },
  mounted() {
      getOneStudentById({ id: this.$route.query.studentId }).then((res) => {
        var { code, result } = res.data;
        if (code === "0000") {
          this.classId = result.classId;
          getClassAllExers({stuClassId: this.classId,stuId:this.$route.query.studentId}).then((res) => {
              var { code, result } = res.data;
              console.log("获取试卷接口响应：");
              console.dir(res);
              if (code === "0000") {
                this.AllExerAnswer=result
                if(this.AllExerAnswer.length!=0){
                      if(sessionStorage.getItem('nowExer')){
                        this.nowExer=parseInt( sessionStorage.getItem('nowExer'))
                      }
                      else{
                        this.nowExer=this.AllExerAnswer[0].exerciseId
                      }
                      this.getSelectExerAnswer()
                      let key=0
                      for(let i in result){
                        if(result[i].exerciseId==this.nowExer){
                          key=i;
                          break;
                        }
                      }
                      this.studentScore=result[key].get_score
                      this.sumScore=result[key].total_score
                }
                
                //this.getSelectExerSumScore()
              }
        });
        }
      });
      
      getTeachers().then(res=>{
              const { code, result } = res.data
              if (code === '0000') {
                  
                  for(let i=0;i<result.length;i++){
                    if(result[i].id==this.$store.state.username){
                      this.tname=result[i].name
                      break;
                    }
                  }
                console.log('教师姓名',this.tname)
              }
              
              

              
            })
      

    
  },
  destroyed(){
    sessionStorage.setItem('nowExer','');
  },
  methods: {
    
    formatBoolean: function ( cellValue) {//格式化Boolean值
                var ret = ''  //你想在页面展示的值
                
                if (cellValue) {
                    ret = "正确"  //根据自己的需求设定
                } else if(cellValue==false){
                    ret = "错误"
                }
                else{
                  ret=""
                }
                
                return ret;
            },
    //查询当前选择试卷做答结果
    getSelectExerAnswer(){
      getStudentExerAnswer({studentId:this.$route.query.studentId,exerciseId:this.nowExer}).then(res=>{
              const { code, result } = res.data
              if (code === '0000') {
                  
                  this.tableData = result
                  
              }
              
              

              
            })
    },
    //查询某套试卷总分
    /*getSelectExerSumScore(){
      getExerSumScore({exerciseId:this.nowExer}).then(res=>{
              const { code, result } = res.data
              if (code === '0000') {
                  
                 this.sumScore=result
              }
              
              

              
            })
    },*/
    selectExer(value){
      console.log('试卷记录',value)
        sessionStorage.setItem('nowExer',this.nowExer)
        this.getSelectExerAnswer()
        let key=0
                for(let i in this.AllExerAnswer){
                  if(this.AllExerAnswer[i].exerciseId==this.nowExer){
                    key=i;
                    break;
                  }
                
              }
              this.studentScore=this.AllExerAnswer[key].get_score
                this.sumScore=this.AllExerAnswer[key].total_score
        //this.getSelectExerSumScore()
        

        
      
    },
    // 按照index命名表格css class
    getClass(index) {
      
      return "result-table-" + index;
    },
    //导出为excel
    saveAsExcel(){
      table2Excel(-1,this.$route.query.studentId+this.$route.query.studentName)
    },
    questionClick(row){
      this.$router.push({ path: '/questionContent',query:{questionId:row.questionId}})
    },
    scoreClick(row){
      this.dialogFormVisible=true
      this.request.studentId=this.$route.query.studentId
      this.request.exerciseId=this.nowExer;
      this.request.questionId=row.questionId
      this.answer=row.refanswer
      this.stuanswer=row.answer
      this.stuidea=row.idea
      this.oldscore=row.score
      this.difficulty=row.difficulty
      
    },
    rightClick(row){
      modifyStudentAnswer({studentId:this.$route.query.studentId,
                           exerciseId:this.nowExer,
                           questionId:row.questionId,
                           answer:row.answer,
                           isRight:!row.isRight,
                           idea:row.idea,
                           score:row.score}).then(res=>{
        const { code, result } = res.data
        if (code === '0000') {
            console.log("成功",result)
            this.$alert( "修改成功", {
            confirmButtonText: "确认",
            callback: (action) => {
              this.$router.go(0)
                },
            });
        }
        else{
          this.$alert('该题未作答，不能更改！')
        }
        

        
      })
      
      //this.$router.go(0)
    },
    modifyScoreClick(){
      this.newscore=this.form.score
      this.request.score=this.form.score
      if(this.form.score<0||this.form.score>100){
        this.$alert('分值不能小于0超过100！')
      }
      else{
        modifyStudentScore(this.request).then(res=>{
        const { code, result } = res.data
        if (code === '0000') {
          let datetime=new Date()
          var year = datetime.getFullYear();
          var month = datetime.getMonth() +1;
          var strDate = datetime.getDate();
          var hour =datetime.getHours();
          var minute = datetime.getMinutes();
          var second = datetime.getSeconds();
          var newdate = year + '-' + month + '-' + strDate + ' ' + hour + ':' + minute + ':' + second
          
          modifyScoreToLog({studentId:this.$route.query.studentId,
                           exerciseId:this.nowExer,
                           questionId:this.request.questionId,
                           answer:this.answer,
                           stuanswer:this.stuanswer,
                           stuidea:this.stuidea,
                           oldscore:this.oldscore,
                           newscore:this.newscore,
                           studentName:this.$route.query.studentName,
                           stuclass:this.$route.query.classId,
                           difficulty:this.difficulty,
                           opid:this.$store.state.username,
                           opname:this.tname,
                           optime:newdate
                          }).then(res=>{
                        const { code, result } = res.data
                        if (code === '0000') {
                            console.log("成功写入日志",result)
                            
                        }
                        else{
                          
                        }
                        

                        
                      })

            console.log("成功",result)
            this.$alert( "修改成功", {
            confirmButtonText: "确认",
            callback: (action) => {
              this.$router.go(0)
                },
            });
        }
        
        else{
          this.$alert('该题未作答，不能更改！')
        }

        
        })
        this.dialogFormVisible=false
        
        //this.$router.go(0)
      }
      
    }
    
   
   
   
    
}
};
</script>

<style>
.el-header {
  padding: 0;
}

.el-table .cell {
  white-space: pre-wrap;
}
#addQuestion {
  display: flex;
  justify-content: flex-end;
}
.paper-page {
  background-color: #eeeeee;
  padding: 10px;
}
.paper-header {
  background-color: white;
  border-radius: 10px;
  box-shadow: 1px 1px 1px rgb(154, 154, 154);
  display: flex;
  flex-direction: row;
  align-items: center;
}
.page-title_2 {
  margin-left: 20px;
  margin-right: 5px;
}
.select-exer{
 
}
.paper-main {
  margin-top: 10px;
  background-color: white;
  border-radius: 10px;

  box-shadow: 1px 1px 1px rgb(154, 154, 154);
}
</style>
